package com.ssyx.controller;

import com.alibaba.fastjson.JSONObject;
import com.ssyx.auth.AuthThreadLocal;
import com.ssyx.constant.RedisConstant;
import com.ssyx.enums.user.User;
import com.ssyx.result.Result;
import com.ssyx.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @program: ssyx-parent
 * @className: WeixinApiController
 * @description: 微信登录类
 * @data: 2024/3/18 13:45
 * @author: ihu
 * @version: 1.0
 **/

@Slf4j
@Api(tags = "微信登录")
@RestController("WeixinApiController")
@RequestMapping("/api/user/weixin")
public class WeixinApiController {
	
	@Resource
	private UserService userService;
	@Resource
	private RedisTemplate<String, Object> redisTemplate;
	
	@ApiOperation(value = "微信登录获取openid(小程序)")
	@GetMapping("/wxLogin/{code}")
	public Result<Map<String, Object>> callback(@PathVariable String code) {
		//获取授权临时票据
		log.info("微信授权服务:{}", code);
		return Result.ok(userService.wxLogin(code));
	}
	
	@PostMapping("/auth/updateUser")
	@ApiOperation(value = "更新用户昵称与头像")
	public Result<?> updateUser(@RequestBody User user) {
		User user1 = userService.getById(AuthThreadLocal.getId());
		//把昵称更新为微信用户
		redisTemplate.delete(RedisConstant.USER_LOGIN_KEY_PREFIX + user.getId());
		user1.setNickName(user.getNickName().replaceAll("[ue000-uefff]", "*"));
		user1.setPhotoUrl(user.getPhotoUrl());
		user1.setSex(user.getSex());
		userService.updateById(user1);
		redisTemplate.opsForValue().set(RedisConstant.USER_LOGIN_KEY_PREFIX + user.getId(),
				JSONObject.toJSONString(userService.getUserLoginVo(user1.getId())), RedisConstant.INFO_TIMEOUT, TimeUnit.DAYS);
		return Result.ok(null);
	}
}